package util

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"os"
)

// ParseYamlFileDataToMap is used to parse yaml format configuration file into the map collection
// file is the yaml file
func ParseYamlFileToMap(file string) (map[string]interface{}, error) {
	data, err := os.ReadFile(file)
	if err != nil {
		return nil, fmt.Errorf("Error reading file1.yaml: %v", err)
	}
	// 定义结构体来解析 YAML 数据
	var dataMap map[string]interface{}

	// 解析第一个 YAML 文件
	if err := yaml.Unmarshal(data, &dataMap); err != nil {
		return nil, fmt.Errorf("Error parsing file1.yaml: %v", err)
	}
	result := make(map[string]interface{})
	flattenMap("", dataMap, result)
	return result, nil
}

// ParseYamlFileDataToMap is used to parse yaml format configuration file data into the map collection
// data is the binary data obtained by reading the yaml file
func ParseYamlDataToMap(data []byte) (map[string]interface{}, error) {
	// 定义结构体来解析 YAML 数据
	var dataMap map[string]interface{}

	// 解析第一个 YAML 文件
	if err := yaml.Unmarshal(data, &dataMap); err != nil {
		return nil, fmt.Errorf("Error parsing file1.yaml: %v", err)
	}
	result := make(map[string]interface{})
	flattenMap("", dataMap, result)
	return result, nil
}

// flattenMap is used to change the multi-level attribute names of the yaml file to Connect the key as a map
func flattenMap(prefix string, data map[string]interface{}, result map[string]interface{}) {
	for key, value := range data {
		var newKey string
		if prefix == "" {
			newKey = key
		} else {
			newKey = prefix + "." + key
		}

		switch v := value.(type) {
		case map[string]interface{}:
			flattenMap(newKey, v, result)
		default:
			result[newKey] = v
		}
	}
}
